<template>
  <div>
    <h2>Stacked Bar Chart</h2>
    <StackedBarChart
        :chartData="chartDataValue"
        :xAxisLabels="myXAxisLabels"
    >
    </StackedBarChart>
  </div>
</template>

<script setup name="TankCharts" lang="ts">
import StackedBarChart from '@/components/TankStatus/StackedBarChart.vue';
import {onMounted, reactive, Ref, ref, onUnmounted } from "vue";
import { getMyChartData} from "@/api/home.js";
//明确的类型定义
interface ChartSeries {
  name: string;
  data: number[];
}

// 初始化带类型的响应式变量
const chartDataValue = ref<ChartSeries[]>([]);
const myXAxisLabels = ref<string[]>([]);
let intervalTimer: number | null = null;
let abortController: AbortController | null = null;

onMounted(() => {
  const fetchData = async () => {
    // 取消上一个未完成的请求
    if (abortController) {
      abortController.abort();
    }
    abortController = new AbortController();

    try {
      await getMyChartDataValue({ signal: abortController.signal });
    } catch (error) {
      if (error.name !== 'AbortError') {
        console.error('请求失败:', error);
      }
    }
  };

  fetchData();
  intervalTimer = setInterval(fetchData, 43_200_000);
});

onUnmounted(() => {
  if (intervalTimer) clearInterval(intervalTimer);
  if (abortController) abortController.abort();
});

const  getMyChartDataValue = async () => {
  getMyChartData().then((res: any) => {
    if(res.code == 200){
      // 创建新数组以触发响应式更新
      chartDataValue.value = res.data.chartDataValue.map((item: any, index: number) => ({
        name: item.name || `默认名称-${index}`,
        data: item.data.map(Number) || []
      }));

      myXAxisLabels.value = [...res.data.myXAxisLabels]; // 创建新数组

      console.log("更新后数据:", JSON.stringify(chartDataValue.value));
    }
      /*for(let i=0;i<res.data.chartDataValue.length;i++){
        chartDataValue.value[i].name = res.data.chartDataValue[i].name
        chartDataValue.value[i].data = res.data.chartDataValue[i].data
      }
      myXAxisLabels.value = res.data.myXAxisLabels;
    }
    console.log("chartDataValue.value"+JSON.stringify(chartDataValue.value))
    console.log("myXAxisLabels.value"+JSON.stringify(myXAxisLabels.value))*/
  });

}


</script>